package com.banshuibao.bsb_android.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.banshuibao.bsb_android.activity.BitmapShowActivity;

/**
 * Created by zyh on 2017/10/10.
 */

public class WebViewUtil {

    /**
     * webview 添加图片点击事件
     **/
    public static void addImageClickListener(Context context, WebView webView) {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new ImageJavascriptInterface(context), "imageListener");
        webView.setWebViewClient(new ImageWebViewClient());
    }

    /**
     * 插入JS为图片增加点击事件
     */
    private static String addImageListener() {

        return "javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imageListener.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()";
    }

    /*
    * 增加点击图片js
    * **/
    public static class ImageWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (view != null) {
                view.loadUrl(url);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (view != null)
                view.loadUrl(addImageListener());
        }
    }

    /**
     * 点击图片回调js方法
     **/
    public static class ImageJavascriptInterface {

        private Context context;

        public ImageJavascriptInterface(Context context) {
            this.context = context;
        }

        /**
         * 点击图片启动新的 ShowImageFromWebActivity，并传入点击图片对应的 url
         * 和页面所有图片对应的 url
         *
         * @param url 点击图片对应的 url
         */
        @android.webkit.JavascriptInterface
        public void openImage(String url) {
            //  XToast.showToast(context, url);
            SharedPreferences.Editor editor = context.getSharedPreferences("webImage", Context.MODE_PRIVATE).edit();
            editor.putString("image_webContent", url).commit();
            Intent it = new Intent(context, BitmapShowActivity.class);
            it.putExtra("webImage", "image_webContent");
            context.startActivity(it);
        }
    }

}
